from PyQt5.QtWidgets import QWidget, QMessageBox, QHBoxLayout,QVBoxLayout, QSlider, QListWidget, QPushButton, QLabel, QFileDialog, QApplication, QFrame
from PyQt5.QtGui import QIcon, QPixmap, QPalette, QBrush
from PyQt5.QtCore import Qt, QUrl, QTimer
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent, QAudioDeviceInfo, QAudioOutput
import os, time, sys
from uiDef import *

DEFAULT_MUSIC_WIN_DIR = "H:/KwDownload/song"
DEFAULT_MUSIC_LIPI4A_DIR = "/home/sipeed/Desktop/tfcard/media/music"

class MusicPlayer(QWidget):
    def __init__(self):
        super().__init__()
        
        self.song_formats = ['mp3', 'm4a', 'flac', 'wav', 'ogg']
        self.songs_list = []
        self.cur_playing_song = ''
        self.is_setURL = False
        self.is_pause = True
        self.is_switching = False
        self.volume = 30 #默认的音量
        if sys.platform.startswith('linux'):
            self.file_path = DEFAULT_MUSIC_LIPI4A_DIR
        else:
            self.file_path = DEFAULT_MUSIC_WIN_DIR
        
        #返回主界面
        self.homeBtn = QPushButton(self)
        self.homeBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_home.png)}")
        self.homeBtn.setFixedSize(30, 30)
        self.headerLabel = QLabel(self)
        self.headerLabel.setText("音乐播放器")
        self.headerLabel.setStyleSheet("color:white")
        self.hBoxHeader = QHBoxLayout()
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.headerLabel)
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.homeBtn)
        
        #音乐列表
        self.musicList = QListWidget()
        #self.musicList.setFrameShape(QFrame.NoFrame)
        self.musicList.setStyleSheet("background-color: transparent;color:white")
        
        #播放器
        self.player = QMediaPlayer()
        #self.player.setVolume(self.volume)

        #进度条
        self.startTimeLabel = QLabel('00:00')
        self.startTimeLabel.setStyleSheet("color:white")
        self.endTimeLabel = QLabel('00:00')
        self.endTimeLabel.setStyleSheet("color:white")
        self.slider = QSlider(Qt.Horizontal, self)
        
        #按钮
        self.playBtn = QPushButton(self)
        self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")
        self.playBtn.setFixedSize(48, 48)
        self.prevBtn = QPushButton(self)
        self.prevBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_prev.png)}")
        self.prevBtn.setFixedSize(48, 48)
        self.nextBtn = QPushButton(self)
        self.nextBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_next.png)}")
        self.nextBtn.setFixedSize(48, 48)
        self.openBtn = QPushButton(self)
        self.openBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_open.png)}")
        self.openBtn.setFixedSize(24, 24)

        #进度条布局
        self.hBoxSlider = QHBoxLayout()
        self.hBoxSlider.addWidget(self.startTimeLabel)
        self.hBoxSlider.addWidget(self.slider)
        self.hBoxSlider.addWidget(self.endTimeLabel)

        #打开与播放布局
        self.hBoxButton = QHBoxLayout()
        self.hBoxButton.addStretch(1)
        self.hBoxButton.addWidget(self.prevBtn)
        self.hBoxButton.addWidget(self.playBtn)
        self.hBoxButton.addWidget(self.nextBtn)
        self.hBoxButton.addStretch(1)
        self.hBoxButton.addWidget(self.openBtn)

        #整体布局
        self.vboxMain = QVBoxLayout()
        self.vboxMain.addLayout(self.hBoxHeader)
        self.vboxMain.addWidget(self.musicList)
        self.vboxMain.addLayout(self.hBoxSlider)
        self.vboxMain.addLayout(self.hBoxButton)
        self.setLayout(self.vboxMain)

        #信号与槽
        self.homeBtn.clicked.connect(self.returnHome)
        self.homeBtn.clicked.connect(self.close)
        self.openBtn.clicked.connect(self.openMusicFloder)
        self.playBtn.clicked.connect(self.playMusic)
        self.prevBtn.clicked.connect(self.prevMusic)
        self.nextBtn.clicked.connect(self.nextMusic)
        self.musicList.itemDoubleClicked.connect(self.doubleClicked)
        self.player.positionChanged.connect(self.updateProgress)
        self.slider.sliderPressed.connect(self.pauseMusic)
        self.slider.sliderMoved.connect(self.changeProgress)
        self.slider.sliderReleased.connect(self.playMusic)
        
        self.initUI()

    # 初始化界面
    def initUI(self):
        self.resize(WIN_WIDTH, WIN_HEIGHT)
        self.setWindowTitle('简易音乐播放器')
        self.setWindowOpacity(0.9) #透明度
        
        if self.file_path != "":
            try:
                self.showMusicList()
            except:
                print("defaut file_path err")
            
        self.show()

    def paintEvent(self, event):
        palette = QPalette()
        pix = QPixmap("resource/bg/bg_music.png").scaled(self.width(),self.height())
        palette.setBrush(QPalette.Background,QBrush(pix))
        self.setPalette(palette)
 
    # 返回主页
    def returnHome(self):
        print("return home")
        from homeUI import mainWindow
        self.homeWindow = mainWindow()
        self.homeWindow.show()

    # 打开文件夹
    def openMusicFloder(self):
        self.file_path = QFileDialog.getExistingDirectory(self, "选取音乐文件夹", './')
        if self.file_path:
            print(self.file_path)
            self.showMusicList()
            self.cur_playing_song = ''
            self.startTimeLabel.setText('00:00')
            self.endTimeLabel.setText('00:00')
            self.slider.setSliderPosition(0)
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")
    
    # 显示音乐列表
    def showMusicList(self):
        self.musicList.clear()
        for song in os.listdir(self.file_path):
            if song.split('.')[-1] in self.song_formats:
                self.songs_list.append([song, os.path.join(self.file_path, song).replace('\\', '/')])
                self.musicList.addItem(song)
        self.musicList.setCurrentRow(0)
        if self.songs_list:
                self.cur_playing_song = self.songs_list[self.musicList.currentRow()][-1]

    # 提示
    def Tips(self, message):
        QMessageBox.about(self, "提示", message)

    # 设置当前播放的音乐
    def setCurPlaying(self):
        self.cur_playing_song = self.songs_list[self.musicList.currentRow()][-1]
        if sys.platform.startswith('linux'):
            media_file = QUrl("file://" + self.cur_playing_song) #Linux中运行使用这句
        else:
            media_file = QUrl(self.cur_playing_song) #Windows中运行使用这句
        print(media_file)
        self.player.setMedia(QMediaContent(media_file))
        self.is_setURL = True

    # 播放/暂停播放
    def playMusic(self):
        if self.musicList.count() == 0:
            self.Tips('当前路径内无可播放的音乐文件')
            return

        if not self.is_setURL:
            print("is_setURL false")
            self.setCurPlaying()
        
        if self.is_pause or self.is_switching:
            print("play")
            self.player.play()
            self.is_pause = False
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_pause.png)}")
        elif (not self.is_pause) and (not self.is_switching):
            print("pause")
            self.player.pause()
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")

    def pauseMusic(self):
        if not self.is_pause:
            print("pause")
            self.player.pause()
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")
 	
    # 上一曲
    def prevMusic(self):
        self.slider.setValue(0)
        if self.musicList.count() == 0:
            self.Tips('当前路径内无可播放的音乐文件')
            return
        pre_row = self.musicList.currentRow()-1 if self.musicList.currentRow() != 0 else self.musicList.count() - 1
        self.musicList.setCurrentRow(pre_row)
        self.is_switching = True
        print("prevMusic")
        self.setCurPlaying()
        self.playMusic()
        self.is_switching = False

    # 下一曲
    def nextMusic(self):
        self.slider.setValue(0)
        if self.musicList.count() == 0:
            self.Tips('当前路径内无可播放的音乐文件')
            return
        next_row = self.musicList.currentRow()+1 if self.musicList.currentRow() != self.musicList.count()-1 else 0
        self.musicList.setCurrentRow(next_row)
        self.is_switching = True
        print("nextMusic")
        self.setCurPlaying()
        self.playMusic()
        self.is_switching = False  

    # 双击歌曲名称播放音乐
    def doubleClicked(self):
        self.slider.setValue(0)
        self.is_switching = True
        print("doubleClicked")
        self.setCurPlaying()
        self.playMusic()
        self.is_switching = False
        
    # 刷新进度条
    def updateProgress(self, num):
        #print("getPlayTime")
        self.slider.setMaximum(self.player.duration())
        self.slider.setValue(num)
        self.startTimeLabel.setText(time.strftime('%M:%S', time.localtime(self.player.position()/1000)))
        self.endTimeLabel.setText(time.strftime('%M:%S', time.localtime(self.player.duration()/1000)))

    # 改变进度
    def changeProgress(self, num):
        self.player.setPosition(num)

    # 确认用户是否要真正退出
    def closeEvent(self, event):
        if __name__ == '__main__':
            reply = QMessageBox.question(self, 'Message',"确定要退出吗？", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                if not self.is_pause:
                    print("stop")
                    self.player.stop()
                event.accept()
            else:
                event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MusicPlayer()
    sys.exit(app.exec_())
